package ModelLayer;
import java.util.ArrayList;

/**
 * The ItemCon class is a container class, where objects of
 * the type Product and Composition (subclasses of Item) can be added and found in a list.
 * The class is incorporated as Singleton.
 * 
 * @author  Jakob K., Mie P., Anna K., Anders A.P., Danny M.P.  
 * @version 1.0
 */
public class ItemCon {

    private ArrayList<Item> items;
    private static ItemCon  instance;

    /**
     * Constructor for an object of class ItemCon.
     */
    private ItemCon() {

        items = new ArrayList<Item>();

    }
   
    /**
     * Singleton. If instance is not created, this method creates the one instance, and returns it.
     * 
     * @return instance     The one instance of ItemCon.
     */
    public static ItemCon getInstance() {

        if (instance == null) {
            instance = new ItemCon();
        }
        return instance;

    }
    
    /**
     * Add an item to the list of items in the container.
     * 
     * @param i     An Item object that is an instance of either Product or Composition.
     * @throws Exception 
     */
    public void addItem(Item i) throws Exception {

        if (!items.contains(i)) {
        	items.add(i);
        }
        else throw new Exception("Varen er allerede tilføjet.");

    }
    
    /**
     * Finds and returns an item in the list by its itemID.
     * 
     * @param itemID        The ID used to find the item.
     * @return              The item if it is found.
     * @throws Exception    If item is not found.
     */
    public Item getItem(int itemID) throws Exception {

        Item    i = null;
        int     index = 0;
        boolean found = false;
        while (index < items.size() && !found) {
            i = items.get(index);
            if (i.getID() == itemID) {
                found = true;
            }
            else {
                index++;
            }
        }
        if (found == true) {
            return items.get(index);
        }
        else {
            throw new IllegalArgumentException("Vare blev ikke fundet");
        }

    }
    
    /**
     * Removes an Item object from the collection.
     * 
     * @param itemID        The ID used to find the item.
     * @throws Exception    If item is not found.
     */
    public void deleteItem(int itemID) throws Exception {

        items.remove(getItem(itemID));

    }
    
    /**
     * Returns the containerlist
     * @return A arraylist containing objects of the type item.
     */
    public ArrayList<Item> getItemList() {

        return items;

    }

}